package com.kkd.kkdapp.activity;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.android_async_http.AsyncHttpResponseHandler;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.manager.HttpCallBack;

import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;


import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 提现密码修改
 * 
 * @author mty
 * 
 */
public class WithdrawUpdateActivity extends BaseActivity implements
		OnClickListener {

	private RelativeLayout update_img;
	private TextView self_phone;
	private String phone; // 手机号
	private EditText true_name; // 真实姓名
	private EditText true_cardid; // 真实身份证号
	private Button update_next; // 下一步
	private EditText verification_ed; // 验证码
	private boolean flag = false;
	// private String version; // 当前App版本号
	private RelativeLayout send_verify; // 获取验证码
	private TextView verfition_visibility;
	private TextView count_down;
	private int time;
	private TextView count_tv;
	private boolean verfitionFlag = true;
	private TimerTask mTimerTask;
	private Timer timer;
	private boolean LOGOINFLAG = true;
	private String patternCoder = "(?<!\\d)\\d{4,6}(?!\\d)";
	// private BroadcastReceiver smsReceiver;
	// private IntentFilter filter2;
	private String strContent;
	private boolean patternflag = true;
	private Dialog loadDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_withdraw_update);
		initView();
		setListener();
		// getSMSVerificationCode();
	}

	/**
	 * 初始化组件
	 */
	public void initView() {
		update_img = (RelativeLayout) this.findViewById(R.id.update_img);
		self_phone = (TextView) this.findViewById(R.id.self_phone);
		phone = PreferenceUtils.getInstance().getPhone(this);
		self_phone.setText(phone.substring(0, 3) + "****"
				+ phone.substring(7, 11));
		true_name = (EditText) this.findViewById(R.id.true_name);
		true_cardid = (EditText) this.findViewById(R.id.true_cardid);
		update_next = (Button) this.findViewById(R.id.update_next);
		verification_ed = (EditText) this.findViewById(R.id.verification_ed);
		send_verify = (RelativeLayout) this.findViewById(R.id.send_verify);
		verfition_visibility = (TextView) this
				.findViewById(R.id.verfition_visibility);
		count_down = (TextView) this.findViewById(R.id.count_down);
		count_tv = (TextView) this.findViewById(R.id.count_tv);
		// try {
		// version = getVersionName();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
	}

	/**
	 * 注册监听事件
	 */
	public void setListener() {
		update_img.setOnClickListener(this);
		update_next.setOnClickListener(this);
		send_verify.setOnClickListener(this);
		true_name.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if ("".equals(true_name.getText().toString())
						|| "".equals(true_cardid.getText().toString())
						|| "".equals(verification_ed.getText().toString())) {
					update_next.setEnabled(false);
					flag = false;
				} else {
					update_next.setEnabled(true);
					flag = true;
				}

				if ("".equals(true_name.getText().toString())
						|| "".equals(true_cardid.getText().toString())) {
					verfition_visibility.setTextColor(0xffb5b5b5);
				} else {
					verfition_visibility.setTextColor(0xff6c54b6);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		true_cardid.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if ("".equals(true_name.getText().toString())
						|| "".equals(true_cardid.getText().toString())
						|| "".equals(verification_ed.getText().toString())) {
					update_next.setEnabled(false);
					flag = false;
				} else {
					update_next.setEnabled(true);
					flag = true;
				}
				if ("".equals(true_name.getText().toString())
						|| "".equals(true_cardid.getText().toString())) {
					verfition_visibility.setTextColor(0xffb5b5b5);
				} else {
					verfition_visibility.setTextColor(0xff6c54b6);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		verification_ed.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if ("".equals(true_name.getText().toString())
						|| "".equals(true_cardid.getText().toString())
						|| "".equals(verification_ed.getText().toString())) {
					update_next.setEnabled(false);
					flag = false;
				} else {
					update_next.setEnabled(true);
					flag = true;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.update_img:
			finish();
			break;
		case R.id.update_next:

			if (flag) {
				if (LOGOINFLAG) {
					LOGOINFLAG = false;
					handler.postDelayed(new Runnable() {

						@Override
						public void run() {
							LOGOINFLAG = true;
						}
					}, 2000);
					updateWithdraw();

				}
			}
			break;
		case R.id.send_verify:
			if (patternflag) {
				patternflag = false;
				if ("".equals(true_name.getText().toString())
						|| true_name.getText().toString() == null
						|| "".equals(true_cardid.getText().toString())
						|| true_cardid.getText().toString() == null) {
					showToast("请把姓名、身份证号填写完整");
				} else {
					if (isIdentity(true_cardid.getText().toString())) {
						if (verfitionFlag) {
							disposeSendVerify();
						}
					} else {
						showToast("请输入正确的身份证号");
					}

				}
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						patternflag = true;
					}
				}, 2000);
			}
			break;
		}

	}

	/**
	 * 处理发送验证码按钮事件
	 */
	public void disposeSendVerify() {
		sendMobileCode();
		verfitionFlag = false;
		// send_verify.setBackgroundResource(R.drawable.unaddbank_bg_tv);
		verfition_visibility.setVisibility(View.GONE);
		count_down.setVisibility(View.VISIBLE);
		count_tv.setVisibility(View.VISIBLE);
		time = 60;

		if (timer == null)
			timer = new Timer();

		if (mTimerTask == null)
			mTimerTask = new TimerTask() {

				@Override
				public void run() {
					handler.sendEmptyMessage(1);
				}
			};

		timer.schedule(mTimerTask, 0, 1000);

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			if (time != 0) {
				count_down.setText(time + "");
				time--;
			} else if (time == 0) {
				// send_verify.setBackgroundResource(R.drawable.addbank_bg_tv);
				verfition_visibility.setVisibility(View.VISIBLE);
				count_down.setVisibility(View.GONE);
				count_tv.setVisibility(View.GONE);
				verfitionFlag = true;
				if (mTimerTask != null) {
					mTimerTask.cancel();
					mTimerTask = null;
				}
			}
		};
	};

	/**
	 * 发送验证码
	 */
	public void sendMobileCode() {
		KkdHttpMagager.getInstance().getWithdrawSendMobileCodeManager(phone, String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						try {
							String responseString = responseBody.toString();
							showToast(R.string.note_message);
						} catch (Exception e) {

							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						// send_verify
						// .setBackgroundResource(R.drawable.addbank_bg_tv);
						verfition_visibility.setVisibility(View.VISIBLE);
						count_down.setVisibility(View.GONE);
						count_tv.setVisibility(View.GONE);
						verfitionFlag = true;
						if (mTimerTask != null) {
							mTimerTask.cancel();
							mTimerTask = null;
						}

						if (timer != null) {
							timer.cancel();
							timer = null;
						}
						showToast(desc);
					}
				});
	}

	/**
	 * 校正验证
	 */
	public void updateWithdraw() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "努力加载中....");
		KkdHttpMagager.getInstance().getReviseWithdreawUpdate( 
				true_name.getText().toString(),
				true_cardid.getText().toString(),
				verification_ed.getText().toString(), String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {

						try {
							Intent intent = new Intent(
									WithdrawUpdateActivity.this,
									UpdateWithdrawSucceedActivity.class);
							startActivity(intent);
							finish();
						} catch (Exception e) {

							e.printStackTrace();
						}
						if (loadDialog != null) {
							loadDialog.dismiss();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
						if (loadDialog != null) {
							loadDialog.dismiss();
						}
					}
				});
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			verification_ed.setText(strContent);
		};
	};

	// /**
	// *
	// * 读取短信验证码
	// */
	// public void getSMSVerificationCode() {
	// filter2 = new IntentFilter();
	// filter2.addAction("android.provider.Telephony.SMS_RECEIVED");
	// filter2.setPriority(Integer.MAX_VALUE);
	// smsReceiver = new BroadcastReceiver() {
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// Object[] objs = (Object[]) intent.getExtras().get("pdus");
	// for (Object obj : objs) {
	// byte[] pdu = (byte[]) obj;
	// SmsMessage sms = SmsMessage.createFromPdu(pdu);
	// // 短信的内容
	// String message = sms.getMessageBody();
	// LogUtil.d("logo", "message     " + message);
	// // 短息的手机号。。+86开头？
	// String from = sms.getOriginatingAddress();
	// LogUtil.d("logo", "from     " + from);
	//
	// if (!TextUtils.isEmpty(from)) {
	// if (message.indexOf("快快贷") != -1
	// || message.indexOf("新浪") != -1) {
	// String code = patternCode(message);
	// if (!TextUtils.isEmpty(code)) {
	// strContent = code;
	// mHandler.sendEmptyMessage(2);
	// }
	// }
	// }
	// }
	// }
	// };
	// registerReceiver(smsReceiver, filter2);
	// }

	/**
	 * 匹配短信中间的4,6个数字（验证码等）
	 * 
	 * @param patternContent
	 * @return
	 */
	private String patternCode(String patternContent) {
		if (TextUtils.isEmpty(patternContent)) {
			return null;
		}
		Pattern p = Pattern.compile(patternCoder);
		Matcher matcher = p.matcher(patternContent);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
	}

}
